import React, { useState, useEffect } from "react"
import { Table } from "antd"
import * as XLSX from "xlsx"
import { saveAs } from "file-saver"
import ExcelJS from "exceljs"

const SpanTable = () => {
  const [tableData, setTableData] = useState([])

  const getTableData = () => {
    const table = [
      {
        firstType: "电器",
        results: [
          {
            secondType: "电视",
            list: [
              {
                name: "小米",
                number: 20,
                price: 800,
                list_type: [
                  {
                    nameType: "小米A",
                    nameTypeNumber: 20,
                    nameTypePrice: 400,
                  },
                  {
                    nameType: "小米B",
                    nameTypeNumber: 200,
                    nameTypePrice: 4000,
                  },
                  {
                    nameType: "小米C",
                    nameTypeNumber: 20,
                    nameTypePrice: 400,
                  },
                  {
                    nameType: "小米D",
                    nameTypeNumber: 20,
                    nameTypePrice: 400,
                  },
                ],
              },
              {
                name: "长虹",
                number: 10,
                price: 500,
                list_type: [
                  {
                    nameType: "长虹A",
                    nameTypeNumber: 20,
                    nameTypePrice: 400,
                  },
                  {
                    nameType: "长虹B",
                    nameTypeNumber: 200,
                    nameTypePrice: 4000,
                  },
                  {
                    nameType: "长虹C",
                    nameTypeNumber: 20,
                    nameTypePrice: 400,
                  },
                  {
                    nameType: "长虹D",
                    nameTypeNumber: 20,
                    nameTypePrice: 400,
                  },
                ],
              },
            ],
          },
          {
            secondType: "冰箱",
            list: [
              {
                name: "美的",
                number: 20,
                price: 1000,
                list_type: [
                  {
                    nameType: "美的A",
                    nameTypeNumber: 20,
                    nameTypePrice: 400,
                  },
                  {
                    nameType: "美的B",
                    nameTypeNumber: 200,
                    nameTypePrice: 4000,
                  },
                  {
                    nameType: "美的C",
                    nameTypeNumber: 20,
                    nameTypePrice: 400,
                  },
                  {
                    nameType: "美的D",
                    nameTypeNumber: 20,
                    nameTypePrice: 400,
                  },
                ],
              },
              {
                name: "海尔",
                number: 10,
                price: 888,
                list_type: [
                  {
                    nameType: "海尔A",
                    nameTypeNumber: 20,
                    nameTypePrice: 400,
                  },
                  {
                    nameType: "海尔B",
                    nameTypeNumber: 200,
                    nameTypePrice: 4000,
                  },
                  {
                    nameType: "海尔C",
                    nameTypeNumber: 20,
                    nameTypePrice: 400,
                  },
                  {
                    nameType: "海尔D",
                    nameTypeNumber: 20,
                    nameTypePrice: 400,
                  },
                ],
              },
            ],
          },
        ],
      },
      {
        firstType: "食物",
        results: [
          {
            secondType: "零食",
            list: [
              {
                name: "坚果",
                number: 50,
                price: 8,
              },
              {
                name: "辣条",
                number: 80,
                price: 3,
              },
            ],
          },
          {
            secondType: "生疏",
            list: [
              {
                name: "青菜",
                number: 100,
                price: 1,
              },
            ],
          },
        ],
      },
    ]

    setTableData(handleSpan(table))
  }

  // 表格合并方法
  const handleSpan = (table, type = 3) => {
    const newData = []
    // 合并
    // 处理合并表格数据
    table.map((item, i) => {
      if (item.results && item.results.length) {
        // console.log(`item`, item)
        // console.log(`i`, i)
        item.results.map((ss, si) => {
          // console.log(`ss`, ss)
          // console.log(`si`, si)
          if (ss.list && ss.list.length) {
            ss.list.map((tt, ti) => {
              // console.log(`tt`, tt)
              // console.log(`ti`, ti)
              if (tt.list_type && tt.list_type.length) {
                tt.list_type.map((yy, yi) => {
                  const newItem = {
                    index: i + 1,
                    id: Math.floor(Math.random() * 10000), //可以引入 nanoid组件生成不重复的id
                    firstType: item.firstType,
                    secondType: ss.secondType,
                    name: tt.name,
                    ...yy,
                  }

                  if (
                    si === 0 &&
                    ti === 0 &&
                    yi === 0 &&
                    tt.list_type.length > 0
                  ) {
                    newItem.oneRowSpan = 16
                  }

                  if (ti === 0 && yi === 0) {
                    newItem.twoRowSpan = 8
                  }

                  // 三级分类
                  if (yi === 0) {
                    newItem.threeRowSpan = tt.list_type.length
                  }

                  newData.push(newItem)
                })
              }
            })
          }
        })
      }
    })

    console.log(`newData`, newData)
    return newData
  }

  useEffect(() => {
    getTableData()
    // handleData(datas)
  }, [])

  const colums = [
    {
      title: "一级分类",
      dataIndex: "firstType",
      key: "firstType",
      onCell: (record, index) => {
        if (record.oneRowSpan) {
          return { rowSpan: record.oneRowSpan }
        } else {
          return { rowSpan: 0 }
        }

        // return {}
      },
    },
    {
      title: "二级分类",
      dataIndex: "secondType",
      key: "secondType",
      onCell: (record, index) => {
        // console.log(`record`, record)

        if (record.twoRowSpan) {
          return { rowSpan: record.twoRowSpan }
        } else {
          return { rowSpan: 0 }
        }

        // return {}
      },
    },
    {
      title: "名称",
      dataIndex: "name",
      key: "name",
      onCell: (record, index) => {
        // console.log(`record`, record)

        if (record.threeRowSpan) {
          return { rowSpan: record.threeRowSpan }
        } else {
          return { rowSpan: 0 }
        }

        // return {}
      },
    },
    {
      title: "名称分类",
      dataIndex: "nameType",
      key: "nameType",
    },
    {
      title: "数量",
      dataIndex: "nameTypeNumber",
      key: "nameTypeNumber",
    },
    {
      title: "价格",
      dataIndex: "nameTypePrice",
      key: "nameTypePrice",
    },
  ]

  const excelColums = [
    {
      header: "一级分类",
      key: "firstType",
      width: 30,
    },
    {
      header: "二级分类",
      key: "secondType",
      width: 30,
      height: 30,
      headerCount: 1,
    },
    {
      header: "三级分类",
      key: "name",
      width: 30,
    },
    {
      header: "名称分类",
      key: "nameType",
      width: 30,
    },
    {
      header: "数量",
      key: "nameTypeNumber",
      width: 30,
    },
    {
      header: "价格",
      key: "nameTypePrice",
      width: 30,
    },
  ]

  const downloadExcel = async () => {
    console.log(`tableData`, tableData)
    const workbook = new ExcelJS.Workbook()
    workbook.creator = "Me"
    workbook.lastModifiedBy = "Her"
    workbook.created = new Date(1985, 8, 30)
    workbook.modified = new Date()
    workbook.lastPrinted = new Date(2016, 9, 27)
    const worksheet = workbook.addWorksheet("My Sheet1")
    const worksheet2 = workbook.addWorksheet("My Sheet2")
    worksheet2.columns = [
      {
        header: "爸爸",
        key: "father",
      },
    ]

    worksheet.columns = excelColums
    // worksheet.header = 7
    worksheet.addRows(tableData)
    // worksheet.spliceRows(20, 0, [
    //   "一级分类",
    //   "二级分类",
    //   "三级分类",
    //   "四级分类",
    // ])
    worksheet.mergeCells("D1", "F1")
    worksheet.mergeCells("A1", "A2")
    worksheet.mergeCells("B1", "B2")
    worksheet.mergeCells("C1", "C2")

    function mergeCells(startRow, startCol, endRow, endCol) {
      const merge = worksheet.getCell(startRow, startCol)

      for (let row = startRow + 1; row <= endRow; row++) {
        for (let col = startCol; col <= endCol; col++) {
          worksheet.getCell(row, col).value = null
        }
      }
      worksheet.mergeCells(startRow, startCol, endRow, endCol)
    }

    // 写入数据
    tableData.forEach((d, index) => {
      const row = index + 3

      if (d.oneRowSpan) {
        mergeCells(row, 1, row + d.oneRowSpan - 1, 1)
        // worksheet.mergeCells(row, 1, row + d.oneRowSpan - 1, 1)
        // console.log(row, 1, row + d.oneRowSpan - 1, 1)
      }
      if (d.twoRowSpan) {
        mergeCells(row, 2, row + d.twoRowSpan - 1, 2)
        // worksheet.mergeCells(row, 2, row + d.twoRowSpan - 1, 2)
      }
      if (d.threeRowSpan) {
        mergeCells(row, 3, row + d.threeRowSpan - 1, 3)
        // worksheet.mergeCells(row, 3, row + d.threeRowSpan - 1, 3)
      }
    })

    // 设置垂直居中
    worksheet.eachRow({ includeEmpty: true }, function (row, rowNumber) {
      row.alignment = { vertical: "middle", horizontal: "center" }
    })

    // 设置第一行和第二行的字体为粗体
    worksheet.getRow(1).font = { bold: true, size: 12 }
    worksheet.getRow(2).font = { bold: true, size: 12 }

    const buffer = await workbook.xlsx.writeBuffer()
    const blob = new Blob([buffer], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    })

    // 保存 Blob 对象到本地文件
    saveAs(blob, "my-workbook.xlsx")
  }

  // const line = [
  //   { header: "厂区", key: "factory", width: 30 },
  //   { header: "产线", key: "line", width: 30 },
  //   { header: "工站", key: "site", width: 30 },
  //   {
  //     header: "合计",
  //     key: "site",
  //     width: 30,
  //     child: [
  //       { id: 41, title: "Zoo 1" },
  //       { id: 42, title: "Zoo 2" },
  //       { id: 44, title: "Zoo 3" },
  //       { id: 45, title: "Zoo 4" },
  //     ],
  //   },
  // ]

  const datass = [
    ["RPT LOT", "前支撑Lot", "sheet id"],
    ["RPT LOT", "前支撑Lot", "sheet id"],
    ["RPT LOT", "前支撑Lot", "sheet id"],
    ["RPT LOT", "前支撑Lot", "sheet id"],
    ["RPT LOT", "前支撑Lot", "sheet id"],
  ]

  const downloadExcelLine = async () => {
    const workbook = new ExcelJS.Workbook()
    workbook.creator = "Me"
    workbook.lastModifiedBy = "Her"
    workbook.created = new Date(1985, 8, 30)
    workbook.modified = new Date()
    workbook.lastPrinted = new Date(2016, 9, 27)
    const worksheet = workbook.addWorksheet("My Sheet1")
    // runColums()
    // worksheet.makeColumns = line
    worksheet.addRows(datass)

    // 设置垂直居中
    worksheet.eachRow({ includeEmpty: true }, function (row, rowNumber) {
      row.alignment = { vertical: "middle", horizontal: "center" }
    })

    const buffer = await workbook.xlsx.writeBuffer()
    const blob = new Blob([buffer], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    })

    // 保存 Blob 对象到本地文件
    saveAs(blob, "my-workbook.xlsx")
  }

  const runColums = (date) => {
    const header = []
    //  1 定义初始化表头信息
    const initHeader = [
      {
        name: "厂区",
        key: "factory",
        width: 30,
        children: [
          {
            header: "厂区1",
            key: "name1",
            with: 15,
          },
          {
            header: "厂区2",
            key: "name2",
            with: 15,
          },
        ],
      },
      {
        header: "产线",
        key: "line",
        width: 30,
      },
      {
        header: "工站",
        key: "site",
        width: 30,
      },
    ]

    header.push(initHeader)
    date.forEach((item) => {
      let new_item = {}
      new_item.header = item
    })
  }

  return (
    <div>
      <h3 style={{ marginTop: "15px" }}>表格合并</h3>
      <button onClick={downloadExcel}>下载成 Excel</button>
      <button onClick={downloadExcelLine}>动态生成header</button>
      {/* <button onClick={ha}>下载</button> */}
      <Table
        bordered
        columns={colums}
        rowKey="id"
        dataSource={tableData}
        pagination={false}
      />
    </div>
  )
}

export default SpanTable
